<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户注册</title>
    <script type="text/javascript">
        window.onload = function () {
            //拿到按钮
            var check = document.getElementById("checkout");
            check.onclick = function () {
                //获取到填写的值
                var uname = document.getElementById("uname").value;
                // alert(uname);
                //创建一个xmlHttpRequest对象
                var xhr = new XMLHttpRequest();
                xhr.open("GET", "/ajax/UserServlet?uname=" + uname, true);
                //在发送前可以读取到状态
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        console.log("xhr", xhr)
                        var responseText = xhr.responseText;
                        if (responseText != ""){
                            alert("no")
                            document.getElementById("myres").value = "用户不可用";
                            document.getElementById("div1").innerHTML = responseText;
                        }else{
                            alert("yes")
                            document.getElementById("myres").value = "用户可用";
                            document.getElementById("div1").innerHTML = responseText;
                        }
                    }

                }
                xhr.send();

            }
        }
    </script>
</head>
<body>
<h1>用户注册</h1>
<form action="/ajax/checkUserServlet" method="post">
    用户名字:<input type="text" name="username" id="uname">
    <input type="button" id="checkout" value="验证用户名">
    <input style="border-width: 0;color: red" type="text" id="myres"><br/><br/>
    用户密码:<input type="password" name="password"><br/><br/>
    电子邮件:<input type="text" name="email"><br/><br/>
    <input type="submit" value="用户注册">
</form>
<h1>返回的 json 数据</h1>
<div id="div1"></div>
</body>
</html>